<template>
  <div class="home">
    <div class="user-info-header">
      <van-button v-if="!isLoggedIn" type="primary" size="small" @click="goToLogin">登录</van-button>
      <div v-else class="user-info">
        <span>欢迎, {{ userInfo.mobile }}</span>
        <van-button size="small" @click="logout">退出</van-button>
      </div>
    </div>

    <van-tabs v-model:active="activeTab" animated>
      <van-tab title="关注" name="关注">
        <div class="dataclass1">
          <van-pull-refresh v-model="state1.isRefresh" @refresh="onRefresh">
            <van-list v-model:loading="state1.isLoading" :finished="state1.finished" finished-text="没有更多了"
              @load="onLoad">
              <van-card v-for="item in dataclass1" :key="item.pid" :title="item.pname" :desc="item.pdesc"
                :thumb="item.pimg1" :price="item.price" @click="goDetail(item.pid)" @click-thumb="goDetail(item.pid)">
                <template #tags>
                  <van-tag plain type="primary">库存: {{ item.stock }}</van-tag>
                </template>
              </van-card>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
      <van-tab title="新闻" name="新闻">
        <div class="news-tab">
          <van-pull-refresh v-model="newsState.isRefresh" @refresh="onNewsRefresh">
            <van-list v-model:loading="newsState.isLoading" :finished="newsState.finished" finished-text="没有更多了"
              @load="onNewsLoad">
              <div v-for="news in newsList" :key="news.id" class="news-item" @click="goToNewsDetail(news)">
                <img :src="news.coverImage" class="news-cover" />
                <div class="news-content">
                  <h3 class="news-title">{{ news.title }}</h3>
                  <div class="news-meta">
                    <span>{{ news.author }}</span>
                    <span>{{ formatNewsTime(news.createTime) }}</span>
                  </div>
                </div>
              </div>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
      <van-tab title="附近" name="附近">
        <div class="dataclass3">
          <van-pull-refresh v-model="state3.isRefresh" @refresh="onRefresh">
            <van-list v-model:loading="state3.isLoading" :finished="state3.finished" finished-text="没有更多了"
              @load="onLoad">
              <van-card v-for="item in dataclass3" :key="item.pid" :title="item.pname" :desc="item.pdesc"
                :thumb="item.pimg1" :price="item.price" @click="goDetail(item.pid)" @click-thumb="goDetail(item.pid)">
                <template #tags>
                  <van-tag plain type="primary">库存: {{ item.stock }}</van-tag>
                </template>
              </van-card>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
      <van-tab title="美食" name="美食">
        <div class="dataclass4">
          <van-pull-refresh v-model="state4.isRefresh" @refresh="onRefresh">
            <van-list v-model:loading="state4.isLoading" :finished="state4.finished" finished-text="没有更多了"
              @load="onLoad">
              <van-card @click="goDetail(item.pid)" @click-thumb="goDetail(item.pid)" v-for="item in dataclass4" :key="item.pid" :title="item.pname" :desc="item.pdesc"
                :thumb="item.pimg1" :price="item.price">
                <template #tags>
                  <van-tag plain type="primary">库存: {{ item.stock }}</van-tag>
                </template>
              </van-card>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
      <van-tab title="旅行" name="旅行">
        <div class="content-list">
          <van-pull-refresh v-model="state5.isRefresh" @refresh="onRefresh">
            <van-list v-model:loading="state5.isLoading" :finished="state5.finished" finished-text="没有更多了"
              @load="onLoad">
              <van-card v-for="item in contentList" :key="item.pid" :title="item.pname" :desc="item.pdesc"
                :thumb="item.pimg1" :price="item.price" @click="goDetail(item.pid)" @click-thumb="goDetail(item.pid)">
                <template #tags>
                  <van-tag plain type="primary">库存: {{ item.stock }}</van-tag>
                </template>
              </van-card>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import axios from 'axios'
import router from "@/router";
import { onBeforeRouteUpdate } from 'vue-router';

// 添加用户信息相关数据
const isLoggedIn = ref(false);
const userInfo = reactive({
  mobile: '',
  token: ''
});

// 检查登录状态
const checkLoginStatus = () => {
  const token = sessionStorage.getItem('token');
  if (token) {
    isLoggedIn.value = true;
    userInfo.token = token;
    // 这里可以从token中解析用户信息，或者发请求获取用户信息
    // 暂时使用默认值
    userInfo.mobile = '138****8888';
  } else {
    isLoggedIn.value = false;
    userInfo.mobile = '';
    userInfo.token = '';
  }
};

// 登录跳转
const goToLogin = () => {
  router.push('/login');
};

// 退出登录
const logout = () => {
  sessionStorage.removeItem('token');
  isLoggedIn.value = false;
  userInfo.mobile = '';
  userInfo.token = '';
};

// 页面加载时检查登录状态
onMounted(() => {
  checkLoginStatus();
  // 初始化加载数据
  onLoad();
});

// 定义产品类型 - 更新以匹配新的数据库结构
interface Product {
  pid?: number;
  pcid?: number;
  scid?: number;
  pname?: string;
  price?: number;
  pimg1?: string;
  pimg2?: string;
  pimg3?: string;
  pdesc?: string;
  pdetails?: string;
  created_at?: string;
  updated_at?: string;
  stock?: number;
  status?: number;
  smallpic?: string; // 新增字段
  sales?: number;    // 新增字段
  collections?: number; // 新增字段
  discount?: number; // 新增字段
  price2?: number;   // 新增字段
  // 添加索引签名以允许其他属性
  [key: string]: any;
}

// 定义分页数据类型
interface PageData {
  records: Product[];
  total: number;
  size: number;
  current: number;
  pages: number;
  [key: string]: any;
}

// 定义新闻类型
interface News {
  id: number;
  title: string;
  coverImage: string;
  createTime: string;
  author: string;
  [key: string]: any;
}

// 为每个标签页创建独立的数据源
const dataclass1 = ref<Product[]>([]) // 关注
const dataclass3 = ref<Product[]>([]) // 附近
const dataclass4 = ref<Product[]>([]) // 美食
const contentList = ref<Product[]>([]) // 旅行
const newsList = ref<News[]>([]) // 新闻

// 为每个标签页创建独立的状态
const state1 = reactive({
  total: 0,
  isRefresh: false,
  isLoading: false,
  finished: false,
  currentPage: 1,
  pageSize: 8
})

const goDetail=(pid)=>{
  router.push(`/goodsDetail/${pid}`)
}

const state3 = reactive({
  total: 0,
  isRefresh: false,
  isLoading: false,
  finished: false,
  currentPage: 1,
  pageSize: 8
})

const state4 = reactive({
  total: 0,
  isRefresh: false,
  isLoading: false,
  finished: false,
  currentPage: 1,
  pageSize: 8
})

const state5 = reactive({
  total: 0,
  isRefresh: false,
  isLoading: false,
  finished: false,
  currentPage: 1,
  pageSize: 8
})

// 新闻状态
const newsState = reactive({
  isRefresh: false,
  isLoading: false,
  finished: false,
  currentPage: 1,
  pageSize: 10
})

const activeTab = ref('美食')

// 创建一个响应式变量来存储当前的刷新状态
const currentRefreshState = ref(false)

// 监听 activeTab 的变化，更新 currentRefreshState
watch(activeTab, (newVal) => {
  // 当切换到新闻标签页时，如果新闻列表为空，则加载数据
  if (newVal === '新闻' && newsList.value.length === 0) {
    onNewsLoad()
  }
})

// 下拉刷新
const onRefresh = () => {
  console.log('onRefresh triggered for tab:', activeTab.value)

  switch (activeTab.value) {
    case '关注':
      state1.currentPage = 1
      dataclass1.value = []
      state1.finished = false
      loadProducts(1, state1.pageSize, dataclass1, state1)
      break
    case '附近':
      state3.currentPage = 1
      dataclass3.value = []
      state3.finished = false
      loadProducts(1, state3.pageSize, dataclass3, state3)
      break
    case '美食':
      state4.currentPage = 1
      dataclass4.value = []
      state4.finished = false
      loadProducts(1, state4.pageSize, dataclass4, state4)
      break
    case '旅行':
      state5.currentPage = 1
      contentList.value = []
      state5.finished = false
      loadProducts(1, state5.pageSize, contentList, state5)
      break
    case '新闻':
      newsState.currentPage = 1
      newsList.value = []
      newsState.finished = false
      loadNews(1)
      break
  }
}

// 加载更多 - 根据当前标签页使用对应的数据源
const onLoad = () => {
  console.log('onLoad triggered for tab:', activeTab.value)

  switch (activeTab.value) {
    case '关注':
      if (state1.finished) {
        state1.isLoading = false
        return
      }
      state1.isLoading = true
      loadProducts(state1.currentPage, state1.pageSize, dataclass1, state1)
      break
    case '附近':
      if (state3.finished) {
        state3.isLoading = false
        return
      }
      state3.isLoading = true
      loadProducts(state3.currentPage, state3.pageSize, dataclass3, state3)
      break
    case '美食':
      if (state4.finished) {
        state4.isLoading = false
        return
      }
      state4.isLoading = true
      loadProducts(state4.currentPage, state4.pageSize, dataclass4, state4)
      break
    case '旅行':
      if (state5.finished) {
        state5.isLoading = false
        return
      }
      state5.isLoading = true
      loadProducts(state5.currentPage, state5.pageSize, contentList, state5)
      break
    case '新闻':
      if (newsState.finished) {
        newsState.isLoading = false
        return
      }
      newsState.isLoading = true
      loadNews(newsState.currentPage)
      break
  }
}

// 加载数据 - 根据当前标签页使用对应的数据源
const loadProducts = async (page: number, size: number, data: any, state: any) => {
  try {
    const response = await axios.get(`/api/goods?page=${page}&limit=${size}`)


    // 处理响应数据，使其适配前端组件
    let pageData: PageData

    // 检查响应数据结构
    if (response.data.records) {
      // 后端返回的是分页数据结构
      pageData = response.data
    } else if (Array.isArray(response.data)) {
      // 后端直接返回数组
      pageData = {
        records: response.data,
        total: response.data.length,
        size: response.data.length,
        current: 1,
        pages: 1
      }
    } else {
      // 其他情况，尝试从对象中提取数据
      const dataArray = response.data.data || response.data.list || response.data.items || []
      pageData = {
        records: Array.isArray(dataArray) ? dataArray : [dataArray],
        total: Array.isArray(dataArray) ? dataArray.length : 1,
        size: Array.isArray(dataArray) ? dataArray.length : 1,
        current: 1,
        pages: 1
      }
    }

    // 如果是刷新操作，清空原有数据
    if (page === 1) {
      data.value = []
    }

    // 添加数据
    data.value.push(...pageData.records.map((item: any) => {
      // 确保必要的字段存在
      return {
        pid: item.pid || item.id || 0,
        pname: item.pname || item.name || item.title || '未知商品',
        price: item.price || item.cost || 0,
        pimg1: item.pimg1 || item.image || item.img || 'https://img.yzcdn.cn/vant/cat.jpeg',
        pdesc: item.pdesc || item.description || item.desc || '',
        stock: item.stock || item.quantity || 0,
        ...item // 保留原始数据的其他字段
      }
    }))

    state.total = pageData.total
    // 关键修改：正确设置 currentPage，以便下次加载下一页
    state.currentPage = pageData.current || page
    state.finished = state.currentPage >= (pageData.pages || 1)
    // 只有在还有更多数据时才增加页码
    if (!state.finished) {
      state.currentPage = (pageData.current || page) + 1
    }
    state.isLoading = false
    state.isRefresh = false
  } catch (error) {
    console.error('加载数据失败:', error)
    // 显示错误提示
    state.isLoading = false
    state.isRefresh = false
    state.finished = true // 避免持续加载

    // 可以添加错误提示
    // Toast.fail('数据加载失败')
  }
}


// 加载新闻数据
const loadNews = async (page: number) => {
  try {
    console.log('正在加载新闻，页码:', page);
    // 这里替换为你的实际新闻API地址
    const response = await axios.get(`/api/news/list?page=${page}&limit=${newsState.pageSize}`)

    // 处理响应数据
    let pageData: any;

    if (response.data.records) {
      // 后端返回的是分页数据结构
      pageData = response.data
    } else if (Array.isArray(response.data)) {
      // 后端直接返回数组
      pageData = {
        records: response.data,
        total: response.data.length,
        size: response.data.length,
        current: 1,
        pages: 1
      }
    } else {
      // 其他情况，尝试从对象中提取数据
      const dataArray = response.data.data || response.data.list || response.data.items || []
      pageData = {
        records: Array.isArray(dataArray) ? dataArray : [dataArray],
        total: Array.isArray(dataArray) ? dataArray.length : 1,
        size: Array.isArray(dataArray) ? dataArray.length : 1,
        current: 1,
        pages: 1
      }
    }

    // 如果是刷新操作，清空原有数据
    if (page === 1) {
      newsList.value = []
    }

    // 添加数据
    newsList.value.push(...pageData.records.map((item: any) => {
      return {
        id: item.id || item.newsId || 0,
        title: item.title || item.name || '未知标题',
        coverImage: item.coverImage || item.image || item.img || 'https://img.yzcdn.cn/vant/cat.jpeg',
        createTime: item.createTime || item.time || new Date().toISOString(),
        author: item.author || item.publisher || '未知作者',
        ...item // 保留原始数据的其他字段
      }
    }))

    // 更新状态
    newsState.currentPage = pageData.current || page
    newsState.finished = newsState.currentPage >= (pageData.pages || 1)
    if (!newsState.finished) {
      newsState.currentPage = (pageData.current || page) + 1
    }
  } catch (error) {
    console.error('加载新闻数据失败:', error)
    newsState.finished = true
  } finally {
    newsState.isLoading = false
    newsState.isRefresh = false
    console.log('新闻加载完成，当前状态:', newsState);
  }
}


// 新闻加载方法
const onNewsLoad = () => {
  console.log('onNewsLoad triggered, current state:', newsState);
  if (newsState.isLoading || newsState.finished) {
    newsState.isLoading = false;
    return;
  }
  newsState.isLoading = true;
  loadNews(newsState.currentPage);
}

// 新闻刷新方法
const onNewsRefresh = () => {
  console.log('onNewsRefresh triggered');
  newsState.currentPage = 1;
  newsList.value = [];
  newsState.finished = false;
  newsState.isRefresh = true;
  loadNews(1);
}

const goToNewsDetail = (news) => {
  router.push({ name: 'newsDetail', params: { id: news.id } })
}

const formatNewsTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString()
}

onMounted(() => {
  // 初始化加载数据
  onLoad()
})
</script>

<style scoped>
.content-list {
  padding: 10px;
  min-height: calc(100vh - 210px);
}

.card-item {
  margin-bottom: 10px;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-content {
  padding: 10px;
}

.card-content h3 {
  font-size: 16px;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.info {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.author {
  margin-right: 8px;
}

.likes {
  margin-left: 4px;
}

.news-tab {
  padding: 10px;
  min-height: calc(100vh - 210px);
}

.news-item {
  display: flex;
  padding: 16px;
  background: white;
  margin-bottom: 10px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.news-cover {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.news-content {
  flex: 1;
  margin-left: 12px;
}

.news-title {
  font-size: 16px;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.news-meta {
  font-size: 12px;
  color: #999;
}

/* 为每个 tab-pane 添加最小高度以确保滑动功能正常工作 */
:deep(.van-tab__panel) {
  min-height: 500px;
}
</style>
